package com.itc.bi.kafaka;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itc.bi.constant.RedisConstant;
import com.itc.bi.entity.DirectDataSetEntity;
import com.itc.bi.entity.DirectoryEntity;
import com.itc.bi.handler.dataSet.SqlCode;
import com.itc.bi.service.impl.ClickHouseJDBCService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: itc-airport-cloud
 * @BelongsPackage: com.itc.bi.kafaka
 * @Author: hecaiy
 * @CreateTime: 2024-07-09  17:27
 * @Description: TODO
 * @Version: 1.0
 */
@Service
public class SyncDataSetService {

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 分页最大值
     */
    private static final Integer PAGESIZE = 10000;

    /**
     * 异步线程处理数据
     * @param dataSetEntity
     * @param directoryEntity
     */
    @Async("asyncServiceExecutor")
    public void insertData(DirectDataSetEntity dataSetEntity,Long dtId,String tableName, SqlCode sqlCode, ClickHouseJDBCService clickHouseJDBCService){
        String key = RedisConstant.DATA_SET_PROCESS_KEY + dtId;
        RLock lock = redissonClient.getLock(key);
        //5分钟等待时间
        //TODO 待测试
        try {
            boolean booleanRedisson = lock.tryLock(5,5, TimeUnit.MINUTES);
//            if (!booleanRedisson) {
//                return;
//            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        try{
            clickHouseJDBCService.emptyTable(tableName);
            IPage page = sqlCode.page(dataSetEntity, 1, 1);
            //2.插入数据
            long total = page.getTotal();
            long pages = (long)Math.ceil((double)total / PAGESIZE);
            for (int i = 1; i <= pages; i++) {
                List<Object> objects = sqlCode.previewData(dataSetEntity,i,PAGESIZE);
                if(CollUtil.isNotEmpty(objects) && objects.size()>0){
                    clickHouseJDBCService.insertDataByTableNameObject(tableName,objects);
                }
            }
        }catch (Exception e){

        }finally {
            lock.unlock();
        }
    }
}
